package com.gx.auth.dao;

import com.gx.auth.common.BaseDAO;
import com.gx.auth.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by gx on 2017/4/3.
 */
@Slf4j
@Repository
public class UserDAO extends BaseDAO {

    private class UserMapper implements RowMapper {
        @Override
        public Object mapRow(ResultSet resultSet, int i) throws SQLException {
            User user = new User();
            user.setId(resultSet.getLong("id"));
            user.setName(resultSet.getString("name"));
            user.setPwd(resultSet.getString("pwd"));
            return user;
        }
    }

    /**
     * 根据用户名密码查询用户
     *
     * @param name
     * @param pwd
     * @return
     */
    public User findUserByinfo(String name, String pwd) {
        String sql = "select * from auth_user where name = ? and pwd = ?";
        try {
            return (User) jdbcTemplate.queryForObject(sql, new Object[]{name, pwd}, new UserMapper());
        } catch (Exception e) {
            log.error("查询getUser异常：" + e.getMessage(), e);
            return null;
        }
    }


    public User findUserByid(int id) {
        String sql = "select * from auth_user where id = ? ";
        try {
            return (User) jdbcTemplate.queryForObject(sql, new Object[]{id}, new UserMapper());
        } catch (Exception e) {
            log.error("查询getUser异常：" + e.getMessage(), e);
            return null;
        }

    }

    public int insertUser(User user) {
        String sql = "insert  auth_user (id,name,pwd) values(?,?,?) ";
        return jdbcTemplate.update(sql, user.getId(), user.getName(), user.getPwd());
    }

    public int updataUserById(User user) {
        String sql = "update  auth_user set name = ? pwd = ? where id = ?";
        return jdbcTemplate.update(sql, user.getId(), user.getName(), user.getPwd());

    }

    public int deleteUserById(Long id) {
        String sql = "delete from auth_user where id = ? ";
        return jdbcTemplate.update(sql, id);

    }

    public Collection<User> findUserByids(Collection<Long> ids) {
        StringBuilder sql = new StringBuilder("select *  from auth_user where id in (");
        Object [] objects = new Object[ids.size()];
        AtomicInteger index = new AtomicInteger();
        ids.forEach(
                (id) -> {
                    sql.append(id).append("?,");
                    objects[index.getAndIncrement()]=id;
                });
        sql.deleteCharAt(sql.length() - 2);
        sql.append(")");
        return jdbcTemplate.query(sql.toString(), ids.toArray(new Object[0]),new UserMapper());
    }

    public List<User> findPage(int page, int size) {
        return null;
    }

}
